package com.xmb.wechat.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.xmb.wechat.R;
import com.xmb.wechat.application.WechatExitApplication;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.definterface.CommonIAndSListener;
import com.xmb.wechat.definterface.EmptyDeliver;
import com.xmb.wechat.definterface.HintListener;
import com.xmb.wechat.definterface.OnChooseMeListener;
import com.xmb.wechat.definterface.OnChooseRoleListener;
import com.xmb.wechat.definterface.PicChooseCallBack;
import com.xmb.wechat.dialog.CommonListDialog;
import com.xmb.wechat.dialog.ExemptionDialog;
import com.xmb.wechat.dialog.OnLeaveHintDialog;
import com.xmb.wechat.dialog.RoleChooseDialog;
import com.xmb.wechat.util.FileUtils;
import com.xmb.wechat.view.wechat.chat.WechatContactAddActivity;
import com.xmb.wechat.view.wechat.chat.WechatContactsActivity;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.ButterKnife;

/**
 * @Author lijiangop
 * @CreateTime 2019/11/14 15:19
 */
public abstract class BaseActivity extends AppCompatActivity {
    //联系人选择
    public static final int REQUEST_CODE_CHOOSE_OTHER_SEND      = 711;
    public static final int REQUEST_CODE_CHOOSE_NEW_ADD_SEND    = 712;
    public static final int REQUEST_CODE_CHOOSE_OTHER_RECEIVE   = 713;
    public static final int REQUEST_CODE_CHOOSE_NEW_ADD_RECEIVE = 714;
    //图片选择
    public static final int REQUEST_CODE_CHOOSE_PIC_WITH_CUT    = 797;
    public static final int REQUEST_CODE_CHOOSE_PIC_WITHOUT_CUT = 799;

    //是否改变状态栏的文字颜色
    protected boolean isChangeStatusBarTxtColor = true;
    protected boolean isFullScreen              = false;

    private int               reslayout;
    //dialog
    private OnLeaveHintDialog mLeaveDialog;
    private ExemptionDialog   mExemptionDialog;
    private RoleChooseDialog  mRoleChooseSenderDialog, mRoleChooseReceiverDialog;
    private CommonListDialog mCommonListDialog;

    public BaseActivity(int resLayout) {
        this.reslayout = resLayout;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (isFullScreen)
            BarUtils.setStatusBarColor(this, getResources().getColor(R.color.transparent));
        super.onCreate(savedInstanceState);
        setContentView(reslayout);
        ButterKnife.bind(this);
        initView();
        WechatExitApplication.getInstance().addActivity(this);
        //修改状态栏文字颜色
        if (isChangeStatusBarTxtColor)
            changeStatusBarTextColor();
    }

    protected void initView() {
    }

    //--------------------------------------------------------------------------公共方法START----------------------------------------------------------------------
    protected void changeStatusBarTextColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    protected void setStatusBarColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(color);
        }
    }

    protected void setNavigationColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setNavigationBarColor(color);
        }
    }

    protected void showStatusBarWithPic() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 修改字体为方形
     *
     * @param textView
     */
    protected void setTypeface(TextView textView) {
        Typeface fromAsset = Typeface.createFromAsset(getAssets(), "fonts/WeChatLqNumber.ttf");
        if (fromAsset != null)
            textView.setTypeface(fromAsset);
    }

    /**
     * 展示免责声明
     */
    protected void showExemption(EmptyDeliver emptyDeliver) {
        //全局配置
        if (!TextUtils.equals(getString(R.string.is_show_exemption), "true")) {
            if (emptyDeliver != null)
                emptyDeliver.onDeliver();
            return;
        }
        if (mExemptionDialog == null) {
            mExemptionDialog = new ExemptionDialog(this, new HintListener() {
                @Override
                public void onConfirm() {
                    if (emptyDeliver != null)
                        emptyDeliver.onDeliver();
                }

                @Override
                public void onCancel() {
                    //doNothing
                }
            });
        }
        mExemptionDialog.show();
    }

    /**
     * 展示免责声明
     */
    protected void showExemption(HintListener hintListener) {
        //全局配置
        if (!TextUtils.equals(getString(R.string.is_show_exemption), "true")) {
            if (hintListener != null)
                hintListener.onConfirm();
            return;
        }
        if (mExemptionDialog == null) {
            mExemptionDialog = new ExemptionDialog(this, hintListener);
        }
        mExemptionDialog.show();
    }

    //角色选择Dialog(发送)
    protected void showRoleChooseSender(Activity activity, boolean isShowMe, boolean isShowWo, OnChooseMeListener listener) {
        showRoleChooseSender(activity, isShowMe, 0, isShowWo, listener);
    }

    /**
     * 角色选择Dialog(发送)
     *
     * @param activity     上下文
     * @param isShowMe     是否显示我的选项
     * @param platformType 平台类型(0 default 微信，1 支付宝，2 qq)
     * @param isShowWo     显示在本人昵称后加上 ‘(我)’
     * @param listener     回调
     */
    protected void showRoleChooseSender(Activity activity, boolean isShowMe, int platformType, boolean isShowWo, OnChooseMeListener listener) {
        if (mRoleChooseSenderDialog == null) {
            mRoleChooseSenderDialog = new RoleChooseDialog(this, new OnChooseRoleListener() {
                @Override
                public void onMeChoose(WechatContactBean mineContactBean) {
                    if (listener != null)
                        listener.onMeChoose(mineContactBean);
                }

                @Override
                public void onOtherChoose() {
                    WechatContactsActivity.startForResult(activity, true, REQUEST_CODE_CHOOSE_OTHER_SEND);
                }

                @Override
                public void onNewAdd() {
                    WechatContactAddActivity.startForResult(activity, true, REQUEST_CODE_CHOOSE_NEW_ADD_SEND);
                }
            });
        }
        if (isShowMe) {
            switch (platformType) {
                case 1:
                    mRoleChooseSenderDialog.setMineValue(WechatContactBean.instanceNewAliPayMe(this, isShowWo));
                    break;
                case 2:
                    mRoleChooseSenderDialog.setMineValue(WechatContactBean.instanceNewQQMe(this, isShowWo));
                    break;
                default:
                    mRoleChooseSenderDialog.setMineValue(WechatContactBean.instanceNewContactMe(this, isShowWo));
                    break;
            }
        } else
            mRoleChooseSenderDialog.hideMe();
        mRoleChooseSenderDialog.show();
    }

    //角色选择Dialog(接收)
    protected void showRoleChooseReceiver(Activity activity, boolean isShowMe, boolean isShowWo, OnChooseMeListener listener) {
        showRoleChooseReceiver(activity, isShowMe, 0, isShowWo, listener);
    }

    /**
     * 角色选择Dialog(接收)
     *
     * @param activity
     * @param listener
     */
    protected void showRoleChooseReceiver(Activity activity, boolean isShowMe, int type, boolean isShowWo, OnChooseMeListener listener) {
        if (mRoleChooseReceiverDialog == null) {
            mRoleChooseReceiverDialog = new RoleChooseDialog(this, new OnChooseRoleListener() {
                @Override
                public void onMeChoose(WechatContactBean mineContactBean) {
                    if (listener != null)
                        listener.onMeChoose(mineContactBean);
                }

                @Override
                public void onOtherChoose() {
                    WechatContactsActivity.startForResult(activity, true, REQUEST_CODE_CHOOSE_OTHER_RECEIVE);
                }

                @Override
                public void onNewAdd() {
                    WechatContactAddActivity.startForResult(activity, true, BaseActivity.REQUEST_CODE_CHOOSE_NEW_ADD_RECEIVE);
                }
            });
        }
        if (isShowMe) {
            switch (type) {
                case 1:
                    mRoleChooseReceiverDialog.setMineValue(WechatContactBean.instanceNewAliPayMe(this, isShowWo));
                    break;
                case 2:
                    mRoleChooseReceiverDialog.setMineValue(WechatContactBean.instanceNewQQMe(this, isShowWo));
                    break;
                default:
                    mRoleChooseReceiverDialog.setMineValue(WechatContactBean.instanceNewContactMe(this, isShowWo));
                    break;
            }
        } else
            mRoleChooseReceiverDialog.hideMe();
        mRoleChooseReceiverDialog.show();
    }

    /**
     * 有编辑内容时的退出提示
     *
     * @return
     */
    protected boolean isNeedShowLeaveHint() {
        return false;
    }

    /**
     * 有编辑内容时的退出提示
     *
     * @param listener
     */
    protected void showNoSaveBeforeLeave(View.OnClickListener listener) {
        if (mLeaveDialog == null) {
            mLeaveDialog = new OnLeaveHintDialog(this, listener);
        }
        mLeaveDialog.show();
    }

    /**
     * 获取图片（直接选择）
     *
     * @param data
     * @return
     */
    public String getPicFromIntent(Intent data) {
        if (data == null) {
            ToastUtils.showShort("图片选择出错");
            return null;
        }
        try {
            Uri uri = data.getData();
            if (null == uri) {
                ToastUtils.showShort("图片选择出错");
                return null;
            }
            String imagePath = getImagePathFromSDCard(this, uri);
            if (TextUtils.isEmpty(imagePath)) {
                ToastUtils.showShort("图片选择出错");
                return null;
            }
            Log.d("pic__choose__result", imagePath);
            return imagePath;
        } catch (Exception e) {
            ToastUtils.showShort("图片选择出错");
            return null;
        }
    }

    /**
     * 获取图片路径
     *
     * @param context Context
     * @param uri     图片 Uri
     * @return 图片路径
     */
    public static String getImagePathFromSDCard(Context context, Uri uri) {
        if (uri == null)
            return "";
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(uri, proj, null, null, null);
            if (cursor == null)
                return null;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * 获取显示名字不带‘（我）’
     *
     * @param me
     * @return
     */
    public String getNameWithMe(String me) {
        if (!TextUtils.isEmpty(me) && me.contains("（我）"))
            me = me.replace("（我）", "");
        return me;
    }

    /**
     * 通用list选择dialog
     *
     * @param data
     * @param listener
     */
    protected void showListDialog(ArrayList data, CommonIAndSListener listener) {
        if (mCommonListDialog == null)
            mCommonListDialog = new CommonListDialog(this, listener);
        mCommonListDialog.setData(data);
        mCommonListDialog.show();
    }

    /**
     * 切换empty与recyclerView的显示
     *
     * @param isShowEmpty
     */
    protected void showEmptyView(boolean isShowEmpty) {
        View empty = findViewById(R.id.ll_empty);
        if (empty != null)
            empty.setVisibility(isShowEmpty ? View.VISIBLE : View.GONE);
        View recyclerView = findViewById(R.id.recyclerView);
        if (recyclerView != null)
            recyclerView.setVisibility(isShowEmpty ? View.GONE : View.VISIBLE);
    }

    //--------------------------------------------------------------------------公共方法END----------------------------------------------------------------------
    private float mRatioX, mRatioY;
    private PicChooseCallBack mPicChooseCallBack;

    public void setPicCallBack(PicChooseCallBack callBack, float ratioX, float ratioY) {
        mPicChooseCallBack = callBack;
        mRatioX = ratioX;
        mRatioY = ratioY;
    }

    private Uri mPicChooseUri;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_PIC_WITHOUT_CUT) {//图片选择不剪切
            if (data == null) {//未选择
                return;
            }
            mPicChooseUri = data.getData();
            if (mPicChooseUri == null) {
                ToastUtils.showShort("图片选择出错");
                return;
            }
            if (mPicChooseCallBack == null)
                return;
            mPicChooseCallBack.onPicChoose(getImagePathFromSDCard(this, mPicChooseUri));
        } else if (requestCode == REQUEST_CODE_CHOOSE_PIC_WITH_CUT) {//图片选择剪切
            if (data == null) {//未选择
                return;
            }
            mPicChooseUri = data.getData();
            if (mPicChooseUri == null) {
                ToastUtils.showShort("图片选择出错");
                return;
            }
            String pathName = "file:///" + FileUtils.getImageCacheDir(this) + File.separator + System.currentTimeMillis() + ".jpg";
            Uri cropPictureTempUri = Uri.parse(pathName);
            //开始裁剪
            UCrop.Options options = new UCrop.Options();
            options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
            if (mRatioX == 0) {
                options.setFreeStyleCropEnabled(true);
                UCrop.of(mPicChooseUri, cropPictureTempUri).withOptions(options).start(this);
            } else
                UCrop.of(mPicChooseUri, cropPictureTempUri).withOptions(options).withAspectRatio(mRatioX, mRatioY).start(this);
        } else if (requestCode == UCrop.REQUEST_CROP) {//剪切成功
            if (data == null)
                return;//选中图片后不剪切
            Uri resultUri = UCrop.getOutput(data);
            if (resultUri == null) {
                ToastUtils.showShort("裁剪出错");
                return;
            }
            if (mPicChooseCallBack == null)
                return;
            mPicChooseCallBack.onPicChoose(resultUri.getPath());
        } else if (resultCode == UCrop.RESULT_ERROR) {//剪切出错
            ToastUtils.showShort("裁剪出错");
            if (mPicChooseCallBack == null)
                return;
            if (mPicChooseUri == null)
                return;
            mPicChooseCallBack.onPicChoose(getImagePathFromSDCard(this, mPicChooseUri));
        }
    }

    /**
     * 有编辑内容时的退出提示
     *
     * @return
     */
    @Override
    public void onBackPressed() {
        if (isNeedShowLeaveHint())
            showNoSaveBeforeLeave(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        else
            super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mExemptionDialog != null) {
            mExemptionDialog.dismiss();
            mExemptionDialog = null;
        }
        if (mLeaveDialog != null) {
            mLeaveDialog.dismiss();
            mLeaveDialog = null;
        }
        if (mRoleChooseSenderDialog != null) {
            mRoleChooseSenderDialog.dismiss();
            mRoleChooseSenderDialog = null;
        }
        if (mRoleChooseReceiverDialog != null) {
            mRoleChooseReceiverDialog.dismiss();
            mRoleChooseReceiverDialog = null;
        }
        if (mCommonListDialog != null) {
            mCommonListDialog.dismiss();
            mCommonListDialog = null;
        }
    }
}
